package api

import (
	"supershare/backend/middleware"
	"supershare/backend/models"

	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
)

// PaymentController 支付相关接口
type PaymentController struct {
	web.Controller
}

// CheckStatus 检查支付状态
func (c *PaymentController) CheckStatus() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取预订单号
	preOrderNo := c.GetString("pre_order_no")
	if preOrderNo == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单号不能为空",
		}
		c.ServeJSON()
		return
	}

	// 获取预订单信息
	preOrder, err := models.GetPreOrderByOrderNo(preOrderNo)
	if err != nil {
		logs.Error("检查支付状态时获取预订单失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取预订单信息失败",
		}
		c.ServeJSON()
		return
	}

	if preOrder == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "预订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查预订单是否属于当前用户
	if preOrder.UserId != member.Id {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权查询此预订单",
		}
		c.ServeJSON()
		return
	}

	// 加盟商权限验证 - 确保会员只能查询自己加盟商的订单
	if member.FranchiseId > 0 && preOrder.FranchiseId != member.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权查询此预订单",
		}
		c.ServeJSON()
		return
	}

	// 构建返回结果
	var status string
	var orderInfo map[string]interface{}

	switch preOrder.Status {
	case models.PreOrderStatusPending:
		status = "pending"
	case models.PreOrderStatusConfirmed:
		status = "paid"
		// 如果已支付，获取关联的订单信息
		if preOrder.OrderId > 0 {
			booking, err := models.GetBookingById(preOrder.OrderId)
			if err == nil && booking != nil {
				orderInfo = map[string]interface{}{
					"order_id":   booking.Id,
					"order_no":   booking.OrderNo,
					"status":     booking.Status,
					"start_time": booking.StartTime,
					"end_time":   booking.EndTime,
				}
			}
		}
	case models.PreOrderStatusCancelled:
		status = "cancelled"
	case models.PreOrderStatusExpired:
		status = "expired"
	default:
		status = "unknown"
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "查询支付状态成功",
		"data": map[string]interface{}{
			"pre_order_id":   preOrder.Id,
			"pre_order_no":   preOrder.PreOrderNo,
			"status":         status,
			"pay_amount":     preOrder.PayAmount,
			"balance_amount": preOrder.BalanceAmount,
			"total_amount":   preOrder.TotalAmount,
			"create_time":    preOrder.CreatedAt,
			"expire_time":    preOrder.ExpireTime,
			"order":          orderInfo,
		},
	}
	c.ServeJSON()
}
